﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using TallyJ1Announcer.Properties;

namespace TallyJ1Announcer.XmlSource
{
	public class ImportFromXml
	{
		public ImportFromXml()
		{
			ErrorMessages = new List<string>();
		}

		public string FilePath
		{
			get;
			private set;
		}

		public XmlCommunity ImportedCommunity
		{
			get;
			private set;
		}

		public List<string> ErrorMessages
		{
			get;
			private set;
		}

		public bool ImportSuccessful
		{
			get;
			private set;
		}

		public bool SourceExists
		{
			get;
			set;
		}

		public ImportFromXml AttachTo(string filePath)
		{
			SourceExists = File.Exists(filePath);
			if (SourceExists)
			{
				FilePath = filePath;
			}
			else
			{
				ErrorMessages.Add(string.Format(Resources.XmlCommunityImporter_FileNotFound_First, filePath));
				FilePath = string.Empty;
			}
			return this;
		}

		public ImportFromXml ImportData()
		{
			if (SourceExists)
			{
				try
				{
					StreamReader file = null;

					var attempts = 10;
					do
					{
						attempts--;
						try
						{
							file = File.OpenText(FilePath);
						}
						catch (Exception)
						{
							if (attempts == 0)
							{
								throw;
							}
							Debugger.Log(0, "Glen", "Waiting for file to save");
							Thread.Sleep(100);
						}
					} while (file==null && attempts >= 0);

					if (file != null)
					{
						ImportedCommunity = IoHelper.ReadXml<XmlCommunity>(ModifyContent(file));
						ImportSuccessful = true;
						ActivePath = FilePath;

						file.Dispose();
					}
					else
					{
						throw new ApplicationException("Unknown error");
					}
				}
				catch (Exception ex)
				{
					ImportedCommunity = null;
					ImportSuccessful = false;
					ErrorMessages.Add(string.Format("Error reading contents of the file ({0}).\n\n{1}", FilePath, ex.AllMessages()));
				}
			}

			return this;
		}

		public string ActivePath { get; private set; }

		StringReader ModifyContent(TextReader file)
		{
			var content = file.ReadToEnd();

			content = content.Replace("Pre-Youth", "PreYouth"); // some versions have wrong code
			content = content.Replace("Voted=\"\"", ""); // can't have empty attribute

			return new StringReader(content);
			//var stream = new MemoryStream();
			//var writer = new StreamWriter(stream);
			//writer.Write(content);
			//writer.Flush();

			//stream.Position = 0;
			//return stream;
		}

		//public static XmlCommunity GetXmlCommunity(out bool successful, out List<string> messages, string communityFilePath)
		//{
		//    var xmlCommunityImporter = new ImportFromXml();

		//    var xmlCommunity = xmlCommunityImporter.AttachTo(communityFilePath).ImportData().ImportedCommunity;
		//    successful = xmlCommunityImporter.ImportSuccessful;
		//    messages = xmlCommunityImporter.ErrorMessages;
		//    return xmlCommunity;
		//}

		public void RevertPathToActive()
		{
			FilePath = ActivePath;
		}
	}
}